<?php

namespace App\Console\Commands;

use App\AwardApplicationFormData;
use App\Project;
use Illuminate\Support\Facades\DB;

class ExportProgressAwardWinningProjects extends Command
{
    protected $signature = 'export-progress-award-winning-projects';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $rows = DB::table('_科学技术进步奖获奖项目名单')->orderBy('序号')->get();
        $count = count($rows);
        foreach ($rows as $i => $row) {
            $num = $i + 1;
            $this->log("$num/$count 序号: {$row->序号} {$row->项目名称}");
            $project = Project::where('project_name', $row->项目名称)
                ->whereNotNull('award')
                ->first();
            if (empty($project)) {
                die("Project not found: {$row->项目名称}");
            }
//            $this->log("Project #{$project->id} {$project->project_name}");
            $formDataRecord = AwardApplicationFormData::find($project->id);
            $formData = json_decode($formDataRecord->form_data, true);
//            dd($formData);
            $completionOrgs = preg_split('#[；、，\s]#u', $formData['basic_situation']['complete_companies']);
            $completionOrgs = array_filter($completionOrgs);
            foreach ($completionOrgs as $org) {
//                $this->log("\t$org");
            }
            $completionPersons = preg_split('#[;；、，]#u', $formData['basic_situation']['complete_people']);
            $completionPersons = array_filter($completionPersons);
            foreach ($completionPersons as &$person) {
                $person = preg_replace('#[\s　]+#u', '', $person);
//                $this->log("\t$person");
            }
            $completionPersons = array_filter($completionPersons);
            $attrs = [
                '牵头完成单位' => $formData['basic_situation']['declare_company'],
                '主要完成单位' => implode('、', $completionOrgs),
                '主要完成单位数量' => count($completionOrgs),
                '主要完成人' => implode('、', $completionPersons),
                '主要完成人数量' => count($completionPersons),
            ];
            DB::table('_科学技术进步奖获奖项目名单')->where('项目名称', $row->项目名称)
                ->update($attrs);
        }
    }
}
